package de.wolvan.dataClient;

import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.*;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import de.wolvan.main.main;
import de.wolvan.references.xim;
import de.wolvan.tools.*;
import de.wolvan.window.*;


/** This example demonstrates how to create a websocket connection to a server. Only the most important callbacks are overloaded. */
public class WS extends WebSocketClient {
	
	public static boolean comesFromSetPin = false;
	
	public WS( URI serverUri , Draft draft ) {
		super( serverUri, draft );
	}

	public WS( URI serverURI ) {
		super( serverURI );
	}

	@Override
	public void onOpen( ServerHandshake handshakedata ) {
		System.out.println( "[WebSocket]Opened Connection to Server " + xim.serverFullPath);
		// if you pan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
		this.send("XIM_OPEN " + xim.build);
	}

	@Override
	public void onMessage( String message ) {
		System.out.println( "[WebSocket]Data received: " + message );
		if(message.startsWith("XIM_AUTH ")) {
			if(comesFromSetPin) {
				comesFromSetPin = false;
				main.c.send("XIM_SETP " + LoginWindow.username.getText() + ";" + SetPin.username.getText());
			} else {
				System.out.println("[XIM-Server]XIM AUTH REQUEST");
				try{
					String[] nonce = message.split("\\s");
					//System.out.println("MD5: " + MD5Tools.stringToMd5(nonce[1] + "mlpixelponies" + MD5Tools.stringToMd5("7677") + "xenixlet"));
					this.send("XIM_AUTH " + LoginWindow.username.getText().toLowerCase().replace("http:", "").replace(".tumblr.com","").replace("/","") + ";" + MD5Tools.stringToMd5(nonce[1] + LoginWindow.username.getText().toLowerCase().replace("http:", "").replace(".tumblr.com","").replace("/","") + MD5Tools.stringToMd5(LoginWindow.pin.getText()) + "xenixlet"));
				}
				catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		else if (message.startsWith("XIM_SERVICE_MSG")) {
			System.out.println("[XIM-Server]SERVICE MESSAGE");
			JOptionPane.showMessageDialog(null, message.split("\\s")[1], "Important Service Message!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_ONE_TAB_PLEASE")) {
			System.out.println("[XIM-Server]ONE CLIENT ONLY");
			JOptionPane.showMessageDialog(null, "You are already logged in somewhere.\nPlease check your browser and any other XIM Clients you may have", "Already logged in!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else if(message.startsWith("XIM_STATUS ")) {
			String[] userStatus = message.substring(11).split("\\n");
			if (userStatus[1].equals("1")) {
				ChatWindow.map.put(userStatus[0], true);
				System.out.println("User " + userStatus[0] + " is online");
			} else {
				ChatWindow.map.put(userStatus[0], false);
				System.out.println("User " + userStatus[0] + " went offline");
			}
			ChatWindow.redrawUserList(-1);
		}
		else if (message.startsWith("XIM_SET_PIN")) {
			System.out.println("[XIM-Server]SET PIN");
			//JOptionPane.showMessageDialog(null, "You have to set your XIM Pin first!\nPlease use the XIM Browser Client for this.", "Set PIN!", 0, null);
			LoginWindow.frame.setVisible(false);
			SetPin.renderGUI();
		}
		else if (message.startsWith("XIM_PIN_ALREADY_SET")) {
			System.out.println("[XIM-Server]PIN ALREADY SET");
			JOptionPane.showMessageDialog(null, "You already have a PIN! If you forgot it, please contact the XKit Support.", "Pin already set!", 0, null);
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_PIN_SET_OK")) {
			System.out.println("[XIM-Server]SET PIN");
			JOptionPane.showMessageDialog(null, "Successfully set PIN. You can now log in!", "PIN set!", 1, null);
			LoginWindow.pin.setText("");
			LoginWindow.renderGUI();
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_AUTH_STATUS 0")) {
			System.out.println("[XIM-Server]LOGIN FAILED");
			JOptionPane.showMessageDialog(null, "Login failed!\nMaybe you used the wrong PIN or wrong Username\nYou can also try again, sometimes it works on the 2nd try.", "Failed to log in!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_AUTH_STATUS 1")) {
			System.out.println("[XIM-Server]LOGIN SUCCESSFUL");
			xim.buddies = data.getProperty(LoginWindow.username.getText() + "_ximBuddies");
			this.send("XIM_BUDDIES " + xim.buddies);
		}
		else if (message.startsWith("XIM_BUDDY_LIST")) {
			String[] userList = message.split("\\n");
			for(int i = 0; i<userList.length; i++) {
				if(!userList[i].startsWith("XIM_BUDDY_LIST")) {
					if(!userList[i].equals(";0")) {
						String[] userListData = userList[i].split(";");
						if(userListData[1].equals("1")) {
							ChatWindow.noFriend.put(userListData[0], false);
							ChatWindow.map.put(userListData[0], true);
							ChatWindow.newMsg.put(userListData[0], false);
							System.out.println("User " + userListData[0] + " is online");
						} else {
							ChatWindow.noFriend.put(userListData[0], false);
							ChatWindow.map.put(userListData[0], false);
							ChatWindow.newMsg.put(userListData[0], false);
							System.out.println("User " + userListData[0] + " is offline");
						}						
					}
				}
			}
			ChatWindow.redrawUserList(-1);
			
			de.wolvan.window.ChatWindow.renderGUI();
			de.wolvan.window.LoginWindow.frame.setVisible(false);
			
		}
		else if (message.startsWith("XIM_BANNED")) {
			System.out.println("[XIM-Server]BANNED");
			JOptionPane.showMessageDialog(null, "You are banned from the Network.\nIf you think this is a mistake, please contact the administrator", "Banned!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_MSG_STATUS")) {
			String[] msgSplit = message.split("\\n");
			
			if (msgSplit[1].equals("0")) {
				System.out.println("Message impossible to send");
				ChatWindow.listModel.addElement("Message impossible to send");
				ChatWindow.listModel2.addElement("Message impossible to send");
			}
			if (msgSplit[1].equals("1")) {
				System.out.println("Message sent");
			}
			if (msgSplit[1].equals("2")) {
				System.out.println("One or more Users offline. Message will be sent when they come online");
				ChatWindow.listModel.addElement("One or more Users offline. Message will be sent when they come online");
				ChatWindow.listModel2.addElement("One or more Users offline. Message will be sent when they come online");
			}
		}
		else if (message.startsWith("XIM_UPGRADE")) {
			System.out.println("[XIM-Server]OUTDATED");
			JOptionPane.showMessageDialog(null, "This client is outdated!\nPlease upgrade!", "Update Client!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_MSG ")) {
			System.out.println("Received message!");
			//JOptionPane.showMessageDialog(null, message.substring(8), "New message", 0, null);
			ChatWindow.listModel.addElement(message.substring(8).split("\\n")[0] + ": " + message.substring(8).split("\\n")[1]);
			if(!(ChatWindow.users.getSelectedValue() == null)) {
				if(!ChatWindow.users.getSelectedValue().toString().replace(" - No Friend", "").replace(" - Online", "").replace(" - Offline", "").replace(" - New Message", "").equals(message.substring(8).split("\\n")[0])) {
					ChatWindow.newMsg.put(message.substring(8).split("\\n")[0], true);
				}
			} else {
				ChatWindow.newMsg.put(message.substring(8).split("\\n")[0], true);
			}
			
			if(!ChatWindow.userListModel.contains(message.substring(8).split("\\n")[0])) {
				ChatWindow.map.put(message.substring(8).split("\\n")[0], false);
				ChatWindow.newMsg.put(message.substring(8).split("\\n")[0], true);
				ChatWindow.noFriend.put(message.substring(8).split("\\n")[0], true);
			}
			
			ChatWindow.redrawUserList(-1);
			ChatWindow.drawChatList();
		}
		else if (message.startsWith("XIM_PROTOCOL_ERROR_SECURITY")) {
			System.out.println("[XIM-Server]SECURITY ERROR");
			JOptionPane.showMessageDialog(null, "You tried to do something without being logged in.\nPlease log in first!", "Please log in!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else if (message.startsWith("XIM_PROTOCOL_ERROR")) {
			System.out.println("[XIM-Server]WRONG PACKAGE FORMAT");
			JOptionPane.showMessageDialog(null, "The Package you sent was not formatted correctly.", "Wrong Package!", 0, null);
			this.close();
			LoginWindow.enableLogin();
		}
		else {
			System.out.println("[XIM-Server]Unknown repsonse");
			LoginWindow.enableLogin();
		}
	}

	@Override
	public void onClose( int code, String reason, boolean remote ) {
		// The codecodes are documented in class org.java_websocket.framing.CloseFrame
		System.out.println( "[WebSocket]Connection closed by " + ( remote ? "remote peer" : "client" ) );
	}

	@Override
	public void onError( Exception ex ) {
		ex.printStackTrace();
		// if the error is fatal then onClose will be called additionally
	}

}
